package com.kyrioscraft.cloud.security.core.social;


import com.kyrioscraft.cloud.security.core.AppSecurityException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.concurrent.TimeUnit;

/**
 * @Author kyrioscraft
 * @Date 2019/1/14 19:07
 * @Description //TODO
 **/

public class AppSignUpUtils {


    private RedisTemplate<Object,Object> redisTemplate;

    private ConnectionFactoryLocator connectionFactoryLocator;

    private UsersConnectionRepository connectionRepository;

    AppSignUpUtils(RedisTemplate<Object,Object> redisTemplate,ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository) {
        this.redisTemplate = redisTemplate;
        this.connectionFactoryLocator = connectionFactoryLocator;
        this.connectionRepository = usersConnectionRepository;
    }

    public void saveConnectionData(WebRequest request, ConnectionData connectionData) {
        redisTemplate.opsForValue().set(getKey(request),connectionData,10, TimeUnit.MINUTES);
    }

    public void doPostSignUp(WebRequest request, String userId) {
        String key = getKey(request);
        if(!redisTemplate.hasKey(key)) {
            throw new AppSecurityException("无法找到缓存的用户社交账号信息");
        }
        ConnectionData connectionData = (ConnectionData) redisTemplate.opsForValue().get(key);
        Connection<?> connection = connectionFactoryLocator.getConnectionFactory(connectionData.getProviderId()).createConnection(connectionData);
        connectionRepository.createConnectionRepository(userId).addConnection(connection);

        redisTemplate.delete(key);
    }

    private String getKey(WebRequest request) {
        String deviceId =request.getHeader("deviceId");
        if(StringUtils.isBlank(deviceId)) {
            throw new AppSecurityException("设备id参数不能为空");
        }
        return "security:social.connect."+deviceId;
    }
}
